import React, { useCallback, useEffect, useState } from "react";
import ReactDOM, { render } from "react-dom";
import { withLogin } from "@/plugins/hoc";
import $axios from "@/plugins/request";
import moment from "moment";
import 'moment/locale/zh-cn';

import { Input, Card, Row, Select, Form, Button, Table, message, Popconfirm, Tag, Space, Image } from 'antd';
moment.locale('zh-cn')

const { Option } = Select;

function List(props) {

  const [queryData, setQueryData] = useState({
    username: "",
    realname: "",
    tel: "",
    email: "",
    role: "",
    page: 1,
    pagesize: 10,
  })
  const [loading, setLoading] = useState(false)
  const [_id] = useState("_id")
  const [selectIds, setSelectIds] = useState([])
  const [datalist, setDatalist] = useState([])
  const [total, setTotal] = useState(0)

  const getDataList = useCallback(async () => {
    setLoading(true)
    const { data: res } = await $axios.get("/api/users", {
      params: queryData
    });
    if (res.code !== 1) return message.warning(res.msg);
    setDatalist(res.data.list)
    setTotal(res.data.total)
    setLoading(false)
  }, [queryData])

  useEffect(() => {
    getDataList()
  }, [getDataList])

  const onFinish = useCallback((values) => {
    setQueryData({ ...queryData, ...values })
  }, [])

  const addItem = useCallback(() => {
    const { history, match } = props;
    history.push(match.path.replace('/list', '') + '/add');
  }, [])

  const editItem = useCallback((id) => {
    return () => {
      const { history, match } = props;
      history.push(match.path.replace('/list', '') + '/edit/' + id);
    }
  }, [])

  const delItem = useCallback((id) => {
    return async () => {
      const { data: res } = await $axios.delete("/api/users/" + id);
      if (res.code !== 1) return message.warning(res.msg);
      message.success(res.msg);
      getDataList();
    }
  }, [])

  const { page, pagesize } = queryData;
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      width: "120px",
    }, {
      title: '姓名',
      dataIndex: 'realname',
      width: "120px",
    }, {
      title: '手机',
      dataIndex: 'tel',
      width: "150px",
    }, {
      title: '邮箱',
      dataIndex: 'email',
      width: "180px",
    }, {
      title: '状态',
      dataIndex: 'state',
      width: "100px",
      render: (text, row, index) => {
        return text ? <Tag color="cyan">启用</Tag> : <Tag color="red">禁用</Tag>
      }
    }, {
      title: '角色',
      dataIndex: 'role',
      width: "100px",
      render: (text, row, index) => {
        return text == '管理员' ? <Tag color="blue">{text}</Tag> : <Tag color="purple">{text}</Tag>
      }
    }, {
      title: '头像',
      dataIndex: 'head',
      width: "100px",
      render: (text, row, index) => {
        return <Image width={40} src={"/api"+ text} />
      }
    }, {
      title: '注册时间',
      dataIndex: 'create_time',
      width: "180px",
      render: (text, row, index) => {
        return moment(text).format("YYYY-MM-DD HH:mm:ss");
      }
    }, {
      title: '修改时间',
      dataIndex: 'update_time',
      width: "180px",
      render: (text, row, index) => {
        return moment(text).format("YYYY-MM-DD HH:mm:ss");
      }
    }, {
      title: '操作',
      width: "200px",
      render: (text, row, index) => {
        return <Space>
          <Button type="primary" size="small" ghost onClick={editItem(row._id)}>编辑</Button>
          <Popconfirm title="确认删除吗?" placement="topRight" okText="确定" okType="danger" cancelText="取消" onConfirm={delItem(row._id)} >
            <Button size="small" danger>删除</Button>
          </Popconfirm>
        </Space>
      }
    }
  ]
  const rowSelection = {
    type: 'checkbox',
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectIds(selectedRowKeys)
    }
  }
  const pagination = {
    size: "small",
    total: total,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total, range) => `共 ${total} 条`,
    pageSizeOptions: [10, 20, 30, 50],
    onChange: (page, pagesize) => {
      setQueryData({ ...queryData, page, pagesize })
    },
  }

  return (
    <Card style={{ width: 'auto', margin: '0 auto' }}>
      <Row>
        <Form name="searchForm" layout="inline" onFinish={onFinish}
          onSubmit={onFinish}
          autoComplete="off">
          <Form.Item name="username">
            <Input placeholder="用户名" autoComplete="off" />
          </Form.Item>
          <Form.Item name="realname">
            <Input placeholder="姓名" autoComplete="off" />
          </Form.Item>
          <Form.Item name="tel">
            <Input placeholder="手机号" autoComplete="off" />
          </Form.Item>
          <Form.Item name="email">
            <Input placeholder="邮箱" autoComplete="off" />
          </Form.Item>
          <Form.Item name="role" initialValue="">
            <Select style={{ width: 120 }}>
              <Option value="">角色</Option>
              <Option value="用户">用户</Option>
              <Option value="管理员">管理员</Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">查询</Button>
          </Form.Item>
          <Form.Item>
            <Button type="primary" ghost onClick={addItem}>添加用户</Button>
          </Form.Item>
        </Form>
      </Row>
      <Row>
        <Table
          columns={columns}
          rowKey={row => row[_id]}
          dataSource={datalist}
          rowSelection={rowSelection}
          pagination={pagination}
          loading={loading}
          scroll={{ x: "1100px", y: 'calc(100vh - 400px)' }}
        />
      </Row>
    </Card >
  )
}
export default List